import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLineEdit, QLabel, QTextEdit, QMessageBox
from db_operations import DatabaseOperations

class OpenGaussApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        
    def initUI(self):
        self.setWindowTitle('OpenGauss 数据库管理系统')
        self.setGeometry(100, 100, 800, 600)
        
        layout = QVBoxLayout()
        
        self.server_label = QLabel('服务器地址:')
        self.server_input = QLineEdit()
        self.dbname_label = QLabel('数据库名称:')
        self.dbname_input = QLineEdit()
        self.user_label = QLabel('用户名:')
        self.user_input = QLineEdit()
        self.password_label = QLabel('密码:')
        self.password_input = QLineEdit()
        self.port_label = QLabel('端口:')
        self.port_input = QLineEdit()
        self.connect_btn = QPushButton('连接数据库')
        self.connect_btn.clicked.connect(self.connect_db)
        self.disconnect_btn = QPushButton('断开连接')
        self.disconnect_btn.clicked.connect(self.disconnect_db)
        self.disconnect_btn.setEnabled(False)  # Initially disabled
        
        self.query_input = QTextEdit()
        self.execute_query_btn = QPushButton('执行')
        self.execute_query_btn.clicked.connect(self.execute_query)
        
        layout.addWidget(self.server_label)
        layout.addWidget(self.server_input)
        layout.addWidget(self.dbname_label)
        layout.addWidget(self.dbname_input)
        layout.addWidget(self.user_label)
        layout.addWidget(self.user_input)
        layout.addWidget(self.password_label)
        layout.addWidget(self.password_input)
        layout.addWidget(self.port_label)
        layout.addWidget(self.port_input)
        layout.addWidget(self.connect_btn)
        layout.addWidget(self.disconnect_btn)
        layout.addWidget(self.query_input)
        layout.addWidget(self.execute_query_btn)
        
        self.setLayout(layout)
        
        self.db = None
        
    def connect_db(self):
        host = self.server_input.text()
        dbname = self.dbname_input.text()
        user = self.user_input.text()
        password = self.password_input.text()
        port = self.port_input.text()
        try:
            self.db = DatabaseOperations(host, dbname, user, password, port)
            QMessageBox.information(self, '连接成功', '连接数据库成功!')
            self.disconnect_btn.setEnabled(True)
            self.connect_btn.setEnabled(False)
        except Exception as e:
            QMessageBox.critical(self, '连接失败', f'连接数据库失败: {str(e)}')
    
    def disconnect_db(self):
        if self.db:
            self.db.close()
            self.db = None
            QMessageBox.information(self, '断开连接', '数据库连接已断开!')
            self.disconnect_btn.setEnabled(False)
            self.connect_btn.setEnabled(True)
    
    def execute_query(self):
        if self.db is None:
            QMessageBox.warning(self, '警告', '请先连接数据库.')
            return
        
        query = self.query_input.toPlainText()
        try:
            if query.strip().lower().startswith('select'):
                result = self.db.fetch_query(query)
                result_str = "\n".join([str(row) for row in result])
                self.query_input.append("\n结果:\n" + result_str)
            else:
                self.db.execute_query(query)
                QMessageBox.information(self, '成功', '命令执行成功!')
        except Exception as e:
            QMessageBox.critical(self, '错误', f'命令执行失败: {str(e)}')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = OpenGaussApp()
    ex.show()
    sys.exit(app.exec_())
